﻿using System;
using System.Collections.Generic;
//using System.Linq;
//using System.Text;
using AMS.DeDuplicator.CommonLayer.Adapter;
using System.IO;
using AMS.DeDuplicator.CommonLayer.Iterator;

namespace AMS.DeDuplicator.CommonLayer.Composite
{
    public class DirectoryComposite : IDirectoryComposite//, IIterable<IFileComponent>, IIterable<IDirectoryComposite>
    {
        List<IDirectoryComposite> _subdirectories;
        List<IFileComponent> _files;

        string _path;
        public string Path { get { return _path; } }

        public int FileCount { get { return _files.Count; } }

        #region Constructor
        public DirectoryComposite(string path)
        {
            InputValidator.ValidateDirectoryExists(path);

            // trim trailing backslash
            if (path.LastIndexOf('\\') == path.Length - 1)
                path = path.Substring(0, path.Length - 1);

            _path = path;

            _subdirectories = new List<IDirectoryComposite>();
            _files = new List<IFileComponent>();

            PopulateDirectories();
            PopulateFiles();
        }

        private void PopulateDirectories()
        {
            foreach (DirectoryInfo dir in Directory.CreateDirectory(_path).GetDirectories())
            {
                this.AddComposite(new DirectoryComposite(dir.FullName));
            }
        }

        private void PopulateFiles()
        {
            foreach (FileInfo file in Directory.CreateDirectory(_path).GetFiles())
            {
                this.AddComponent(new FileComponent(this, file.Name));
            }
        } 
        #endregion

        public IIterator<IDirectoryComposite> GetDirectories()
        {
            return new EnumeratorAdapter<IDirectoryComposite>(_subdirectories.GetEnumerator());
        }
        // what about iterating over all directories, recursively?

        public IIterator<IFileComponent> GetFiles()
        {
            return new EnumeratorAdapter<IFileComponent>(_files.GetEnumerator());
        }
        // what about iterating over all files, recursively?

        public void AddComposite(IDirectoryComposite composite)
        {
            InputValidator.ValidateNotNull(composite);
            _subdirectories.Add(composite);
        }

        public void AddComponent(IFileComponent component)
        {
            InputValidator.ValidateNotNull(component);
            _files.Add(component);
        }
    }
}
